# !/usr/bin/env python
# coding:utf-8

from telnetlib import Telnet
import tkinter as tk
import pandas as pd
import time
import os

tn = Telnet()

fail_txt = 'log/telne_failhost.txt'     # 存放未连接成功的主机
failtxt = open(fail_txt, 'a',encoding="utf-8")

sentence ='Error'   #成功检测语句


class Telnet_In(tk.Toplevel):
    def __init__(self, parent):
        
        super().__init__(parent)
        # 创建窗口
        self.title("Telnet批量执行工具")
        self.geometry('800x600')
        self.minsize(400,300)  # 最小尺寸
        self.maxsize(800,600)  # 最大尺寸

        ####标题####第一行####
        lb0 = tk.Label(self, text='Telnet批量执行工具', font=('黑体', 24))
        lb0.place(relx=0.1, rely=0.02, relwidth=0.8, relheight=0.1)

        # 创建打开文件按钮和开始执行按钮
        open_button = tk.Button(self, text="创建模板", command=self.create_file)
        open_button.place(relx=0.72, rely=0.18, relwidth=0.15, relheight=0.08)

        open_button = tk.Button(self, text="编辑模板", command=self.open_file)
        open_button.place(relx=0.72, rely=0.3, relwidth=0.15, relheight=0.08)

        start_button = tk.Button(self, text="开始执行", command=self.start_execution)
        start_button.place(relx=0.72, rely=0.42, relwidth=0.15, relheight=0.08)

        openlog1 = tk.Button(self, text='打开日志', command=self.openlog)
        openlog1.place(relx=0.72, rely=0.54, relwidth=0.15, relheight=0.08)

        dellog1 = tk.Button(self, text='删除日志', command=self.dellog)
        dellog1.place(relx=0.72, rely=0.66, relwidth=0.15, relheight=0.08)

        ztxtdel = tk.Button(self, text='清空输出', command=self.txtdel)
        ztxtdel.place(relx=0.72, rely=0.78, relwidth=0.15, relheight=0.08)

        self.txt = tk.Text(self)
        self.txt.insert(0.0,
                "工具执行过程中会卡顿并无回显，请不要多次点击，耐心等待执行完成。\n")
        self.txt.place(relx=0.1, rely=0.18, relwidth=0.6, relheight=0.72)

        by = tk.Label(self, text='version：1.2  |  by:背包的小迟')
        by.place(relx=0.7, rely=0.93, relwidth=0.3, relheight=0.05)



    #模板创建
    def create_file(self):
        if os.path.isfile('telnet.xlsx'):
            self.txt.insert(tk.END, "模板已存在\n")
        else:
            df = pd.DataFrame(columns=['ip', 'username', 'password', 'command'])
            df.to_excel('telnet.xlsx', index=False)
            self.txt.insert(tk.END, "模板已创建\n")

    #编辑模板
    def open_file(self):
        os.startfile('telnet.xlsx')

    #开始执行
    def start_execution(self):
        print("开始执行")
        df = pd.read_excel("telnet.xlsx",sheet_name='Sheet1')
        self.txt.delete(1.0, "end")  # 清空输出
        self.log = open('log/telnet_log.txt', 'a')
        for index, row in df.iterrows():
            ip = row['ip']
            username = row['username']
            password = row['password']
            command = row['command']
            self.telnet(ip, username, password, command)
            tn.close()
        # 关闭文件写入
        self.log.close()

        #'定义telnet函数，用于登陆设备'
    def telnet(self,ip, username, password, command):
        print("-------------------------------------------------------------------------------", file=self.log)
        print("正在处理...host:%s\n" % ip,file=self.log)  #输出正在处理的主机信息到日志
        print("-------------------------------------------------------------------------------", file=self.log)

        self.txt.insert(tk.END, "-------------------------------------------------------------------\n")
        self.txt.insert(tk.END, "host:%s\n" % ip)  # 输出正在处理的主机信息到对话框
        self.txt.insert(tk.END, "-------------------------------------------------------------------\n")

        try:#尝试连接主机
            tn.open(ip, port=23,timeout=1)
            self.txt.insert(tk.END, "连接成功，开始登录！ \n")
            print("连接成功，开始登录！", file = self.log)
            try:#尝试登录主机
                #'输入用户名'
                tn.read_until(b'Username:', timeout=1)
                tn.write(username.encode() + b'\n')
                rely = tn.expect([], timeout=1)[2].decode().strip()  # 读显
                self.txt.insert(tk.END, rely )
                print( rely, file = self.log )

                #'输入密码'
                tn.read_until(b'Password:', timeout=1)
                tn.write(password.encode() + b'\n')
                rely = tn.expect([], timeout=1)[2].decode().strip()
                self.txt.insert( tk.END, rely + "\n")
                print( rely, file = self.log )

                #'进去特权模式' 思科系交换机使用
                #if enable is not None:
                #    tn.write(b'sys\n')
                #    tn.write(enable.encode() + b'\n')
                #    if verbose:
                #        rely = tn.expect([], timeout=1)[2].decode().strip()
                #        print(rely)
                #        time.sleep(1)

                #判断是否登录成功
                #rely = tn.read_very_eager().decode()

                if sentence not in rely:#检测登录成功语句
                    self.txt.insert(tk.END, "登录成功，开始执行脚本！ \n")
                    print("登录成功，开始执行脚本！", file = self.log)
                    try:
                        comm = command.split("\n")
                        for com in comm:
                            tn.write(com.encode().strip() + b'\n')
                            time.sleep(2)
                            rely = tn.read_very_eager().decode()
                            self.txt.insert( tk.END, rely+"\n")
                            print( rely, file = self.log)
                        self.txt.insert(tk.END, "脚本执行完毕，关闭连接！ \n")
                        print("脚本执行完毕，关闭连接！", file = self.log)
                    except:
                        self.txt.insert(tk.END, "脚本执行错误！ \n")
                        print("脚本执行错误！", file = self.log)
                else:
                    self.txt.insert(tk.END, "登陆失败，用户名或密码错误！ \n")
                    print("登陆失败，用户名或密码错误！", file = self.log)
                    fail_enable = False 
                    if fail_enable == True :
                        print('%s登陆失败，用户名或密码错误' % ip, file = failtxt)
                    return
            except:
                self.txt.insert(tk.END, "登陆失败，用户名或密码错误！ \n")
                print("登陆失败，用户名或密码错误！", file = self.log)
        except:
            self.txt.insert(tk.END, "连接失败！ \n")
            print("连接失败！", file = self.log)
            fail_enable = False 
            if fail_enable == True :
                print('%s连接失败！' % ip, file = failtxt)
            return
        
    def openlog(self):
        try:
            os.startfile('log\\telnet_log.txt')
        except:
            self.txt.insert(tk.END, "打开失败，文件不存在 \n")


    def dellog(self):
        try:
            os.remove('log\\telnet_log.txt')
            self.txt.insert(tk.END, "删除成功\n")
        except:
            self.txt.insert(tk.END, "删除失败，文件不存在 \n")
    
    def txtdel(self):  # 清空输出
        self.txt.delete(1.0, "end")  # 清空输出